package com.jy.framework.config;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.jy.api.shiro.filter.ApiTokenSessionFilter;
import com.jy.api.shiro.realm.ApiUserRealm;
import com.jy.framework.sys.shiro.CredentialsMatcher;
import com.jy.framework.sys.shiro.RedisShiroSessionDAO;
import com.jy.framework.sys.shiro.UsernamePasswordUserTypeToken;
import com.jy.framework.sys.shiro.exten.AuthorizationAttributeSourceAdvisor;
import com.jy.framework.sys.shiro.UserRealm;
import com.jy.framework.utils.Global;
import com.jy.framework.utils.RedisUtils;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Shiro的配置文件
 *
 * @author Mark sunlightcs@gmail.com
 * @since 3.0.0 2017-09-27
 */
@Configuration
public class ShiroConfig {


    @Bean("sessionManager")
    @DependsOn("redisShiroSessionDAO")
    public SessionManager sessionManager(RedisShiroSessionDAO redisShiroSessionDAO,
                                         @Value("${jy.redis.open}") boolean redisOpen,
                                         @Value("${jy.shiro.redis}") boolean shiroRedis) {
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        //设置session过期时间为1小时(单位：毫秒)，默认为30分钟
        sessionManager.setGlobalSessionTimeout(60 * 60 * 1000);
        sessionManager.setSessionValidationSchedulerEnabled(true);
        sessionManager.setSessionIdUrlRewritingEnabled(false);

        //如果开启redis缓存且renren.shiro.redis=true，则shiro session存到redis里
        if (redisOpen && shiroRedis) {
            sessionManager.setSessionDAO(redisShiroSessionDAO);
        }
        return sessionManager;
    }

    @Bean("securityManager")
    @DependsOn({"credentialsMatcher","userRealm","sessionManager"})
    public SecurityManager securityManager(CredentialsMatcher credentialsMatcher, UserRealm userRealm, SessionManager sessionManager) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        userRealm.setAuthenticationTokenClass(UsernamePasswordUserTypeToken.class);
        userRealm.setCredentialsMatcher(credentialsMatcher);
        securityManager.setRealm(userRealm);
//        ModularRealmAuthenticator ac=new ModularRealmAuthenticator();
//        ac.setAuthenticationStrategy(new FirstSuccessfulStrategy());
//        securityManager.setAuthenticator(ac);
        securityManager.setSessionManager(sessionManager);
        return securityManager;
    }


    @Bean("shiroFilter")
    @DependsOn({"securityManager"})
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager,@Value("${jy.shiro.appFilterMap}") String appFilterMap) {
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        shiroFilter.setSecurityManager(securityManager);

        shiroFilter.setLoginUrl("/login.html");
        shiroFilter.setUnauthorizedUrl("/");


        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/swagger/**", "anon");
        filterMap.put("/v2/api-docs", "anon");
        filterMap.put("/swagger-ui.html", "anon");
//        filterMap.put("/webjars/**", "anon");
        filterMap.put("/swagger-resources/**", "anon");
        filterMap.put("/v2/api-docs-ext = anon", "anon");
        filterMap.put("/webjars/static/**", "anon");
//        swagger bootsrap ui
        filterMap.put("/doc.html", "anon");
        filterMap.put("/webjars/bycdao-ui/**", "anon");

//      系统配置
        filterMap.put("/sys/config/get/**", "anon");
        //        静态资源
        filterMap.put("/static/files/**", "anon");
        filterMap.put("/webjars/login.html", "anon");
//        两种登录方式
        filterMap.put("/login/**", "anon");

        filterMap.put("/favicon.ico", "anon");
        filterMap.put("/captcha.jpg", "anon");
        JSONObject json = JSONObject.parseObject(appFilterMap);
        if (!CollectionUtil.isEmpty(json)){
            Map<String, String> collect = json.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, v-> (String)v.getValue()));
            filterMap.putAll(collect);
        }
//      shiro
        filterMap.put("/api/**", "apiSession,user");
        filterMap.put("/sys/**", "apiSession,user");
        filterMap.put("/diy/**", "apiSession,user");
        filterMap.put("/qr/**", "apiSession,user");
//,"/anon/productionqr/**" : "anon"

        filterMap.put("/**", "authc");
        shiroFilter.setFilterChainDefinitionMap(filterMap);

        // Filter 过滤器
        Map<String, Filter> filters = new LinkedHashMap<>();
        filters.put("apiSession", apiTokenSessionFilter());
        shiroFilter.setFilters(filters);

        return shiroFilter;
    }

    @Bean("lifecycleBeanPostProcessor")
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }

    /**
     * api 访问控制
     */
    @Bean
    public ApiTokenSessionFilter apiTokenSessionFilter() {
        ApiTokenSessionFilter filter = new ApiTokenSessionFilter();
//        filter.setLoginUrl(loginUrl);
        return filter;
    }
    @Bean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator proxyCreator = new DefaultAdvisorAutoProxyCreator();
        proxyCreator.setProxyTargetClass(true);
        return proxyCreator;
    }

    @Bean
    @DependsOn({"securityManager"})
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }

    /**
     * 自定义Realm创建
     *
     * @return
     */
    @Bean
    @DependsOn({"credentialsMatcher"})
    public UserRealm userRealm(CredentialsMatcher credentialsMatcher) {
        ApiUserRealm myShiroRealm = new ApiUserRealm();
        //将自定义的令牌set到了Realm
        myShiroRealm.setCredentialsMatcher(credentialsMatcher);
        return myShiroRealm;
    }


    @Bean("credentialsMatcher")
    public CredentialsMatcher credentialsMatcher() {
        return new CredentialsMatcher();
    }


    @Bean("redisUtils")
    public RedisUtils redisUtils(@Value("${jy.redis.open}") boolean redisOpen) {
        if (redisOpen) {
            return new RedisUtils();
        }else {
            return null;
        }
    }

    @Bean("redisShiroSessionDAO")
    public RedisShiroSessionDAO redisShiroSessionDAO(@Value("${jy.redis.open}") boolean redisOpen,@Value("${jy.shiro.redis}") boolean shiroRedis) {
        if (redisOpen && shiroRedis) {
            return new RedisShiroSessionDAO();
        } else {
            return null;
        }
    }

}
